<!DOCTYPE html>
<html>
<head>
    <title>提瓦特小助手</title>
    <style>
        body { 
            max-width: 800px; 
            margin: 0 auto; 
            padding: 20px; 
            font-family: Arial, sans-serif;
            background-color: #f5f5f5;
        }
        #chatbox { 
            border: 1px solid #ddd; 
            height: 500px; 
            overflow-y: auto; 
            padding: 20px; 
            margin-bottom: 20px;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .message { 
            margin: 10px 0; 
            padding: 12px; 
            border-radius: 8px; 
            line-height: 1.5;
        }
        .user-message { 
            background: #e3f2fd; 
            margin-left: 20%;
            border-bottom-right-radius: 4px;
        }
        .assistant-message { 
            background: #f8f9fa; 
            margin-right: 20%;
            border-bottom-left-radius: 4px;
        }
        #input-box { 
            display: flex; 
            gap: 10px;
        }
        #user-input { 
            flex: 1; 
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-size: 16px;
        }
        button { 
            padding: 12px 24px; 
            background: #4CAF50; 
            color: white; 
            border: none; 
            border-radius: 8px;
            cursor: pointer;
            font-size: 16px;
            transition: background 0.3s;
        }
        button:hover {
            background: #45a049;
        }
        .welcome-message {
            text-align: center;
            color: #2196F3;
            margin-bottom: 20px;
            font-size: 24px;
        }
    </style>
</head>
<body>
    <h1 class="welcome-message">提瓦特小助手</h1>
    <div id="chatbox"></div>
    <div id="input-box">
        <input type="text" id="user-input" placeholder="请输入您的问题，比如：请推荐胡桃的配队...">
        <button onclick="sendMessage()">发送</button>
    </div>

    <script>
        let messages = [
            { 
                role: 'system', 
                content: '你是一位来自提瓦特大陆的冒险家指导者，精通原神游戏的各个方面。你可以提供角色攻略、配队推荐、深境螺旋攻略等专业建议。'
            }
        ];

        // 添加欢迎消息
        window.onload = function() {
            const chatbox = document.getElementById('chatbox');
            chatbox.innerHTML = `<div class="message assistant-message">
                欢迎来到提瓦特大陆！我是你的冒险指导，让我们开始愉快的旅程吧～<br><br>
                你可以询问我：<br>
                1. 角色攻略（例如：请介绍雷电将军的玩法）<br>
                2. 配队推荐（例如：请推荐胡桃的最佳配队）<br>
                3. 深境螺旋攻略<br>
                4. 活动玩法指南<br>
                5. 圣遗物搭配建议
            </div>`;
        };

        async function sendMessage() {
            const userInput = document.getElementById('user-input');
            const chatbox = document.getElementById('chatbox');
            
            if (!userInput.value.trim()) return;

            // 添加用户消息
            messages.push({ role: 'user', content: userInput.value });
            chatbox.innerHTML += `<div class="message user-message">${userInput.value}</div>`;
            
            // 创建等待中的助理消息
            const assistantMsgDiv = document.createElement('div');
            assistantMsgDiv.className = 'message assistant-message';
            chatbox.appendChild(assistantMsgDiv);
            let finalMessages = null;

            try {
                const response = await fetch('http://localhost:8001/chat', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ messages })
                });

                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let assistantResponse = '';
                let jsonBuffer = '';

                while (true) {
                    const { done, value } = await reader.read();
                    if (done) break;

                    const chunk = decoder.decode(value);
                    jsonBuffer += chunk;

                    while (jsonBuffer.includes('\n\n')) {
                        const splitIndex = jsonBuffer.indexOf('\n\n');
                        const line = jsonBuffer.substring(0, splitIndex);
                        jsonBuffer = jsonBuffer.substring(splitIndex + 2);

                        if (line.startsWith('data: ')) {
                            try {
                                const event = JSON.parse(line.substring(6));
                                if (event.token) {
                                    assistantResponse += event.token;
                                    assistantMsgDiv.innerHTML = assistantResponse; 
                                }
                                if (event.messages) {
                                    finalMessages = event.messages;
                                }
                            } catch (e) {
                                console.warn('JSON解析失败:', e);
                            }
                        }
                    }
                }

                messages = finalMessages || messages;
                userInput.value = '';
                chatbox.scrollTop = chatbox.scrollHeight;
            } catch (error) {
                console.error('请求错误:', error);
                assistantMsgDiv.innerHTML = '派蒙暂时遇到了一些小问题，请稍后再试～';
            }
        }

        // 支持回车发送
        document.getElementById('user-input').addEventListener('keypress', (e) => {
            if (e.key === 'Enter') sendMessage();
        });
    </script>
</body>
</html>